/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.helper;

import java.io.IOException;
import java.util.Collections;

import javax.jdo.PersistenceManager;

import net.oauth.OAuthException;
import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.dhpollack.rotogss.data.AppConfig;
import com.dhpollack.rotogss.data.RotoGSSUsers;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;

/**
 * @author davidpl
 *
 */
public class SimpleYqlHelper {
	
	private static AppConfig APP_CONFIG = AppHelper.get();
	
	private static final String CONSUMER_KEY = APP_CONFIG.getYahooConsumerKey();
	
	private static final String CONSUMER_SECRET = APP_CONFIG.getYahooConsumerSecret();
	
	private static final String CALLBACK_URL = APP_CONFIG.getBaseUrl() + "/simpleyqlcallback/";
	
	private static CacheFactory cacheFactory;
	
	private String user;
	
	private Key userKey;
	
	private Api api = ApiFactory.getApiInstance(
							CONSUMER_KEY,
							CONSUMER_SECRET,
							CALLBACK_URL,
							false, null);
		
	private Entity rUser;
	
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	private Cache cache;
	
	private String authData;
	
	public SimpleYqlHelper()
	throws CacheException {
		setCache();
	}
	
	public SimpleYqlHelper(String user)
	throws CacheException, EntityNotFoundException {
		setUser(user);
		setCache();
	}
	
	public String getUser() {
		return user;
	}
	
	public void setUser(String user) throws EntityNotFoundException {
		this.user = user;
		this.userKey = KeyFactory.createKey(RotoGSSUsers.class.getSimpleName(),user);
		getUserFromDb();
	}
	
	public void setCache() throws CacheException {
        cacheFactory = CacheManager.getInstance().getCacheFactory();
        cache = cacheFactory.createCache(Collections.emptyMap());
		
	}
	
	public void getUserFromDb() throws EntityNotFoundException {
		rUser = datastore.get(userKey);
		Text authTemp = (Text) rUser.getProperty("yahooOAuthData");
		authData = authTemp.getValue();
	}

	public String sendQuery2(String url) throws OAuthException, IOException, EntityNotFoundException {
		QueryResult qr = api.query2(url, authData);
		
	    // Update token, if needed (for future requests)
	    if (qr != null && !qr.getAuthdata().equals(authData)) {
	    	Text newAuth = new Text(qr.getAuthdata());
	    	rUser.setProperty("yahooOAuthData", newAuth);
	    	userKey = datastore.put(rUser);
	    	getUserFromDb();
	    }
	    
	    String xml = qr.getText();
		
	    putXmlIntoCache(url, xml);
		
		return xml;

	}
	
	public String getQuery(String url) throws OAuthException, IOException, EntityNotFoundException {
		
		String xml = getXmlFromCache(url);
		
		if(xml == null) {
			xml = sendQuery2(url);
		}
		
		return xml;
		
		
	}
	
	private String getXmlFromCache(String url) {
		// TODO Auto-generated method stub
		String memcacheKey = user + "-" + url;
		String r;
		if(cache.containsKey(memcacheKey)) {
			r = (String) cache.get(memcacheKey);
		} else {
			r = null;
		}
		
		return r;
	}

	public void putXmlIntoCache(String url, String xml) {
		String key = user + "-" + url;
		cache.put(key, xml);
	}
	
}
